package helper

import (
	"fmt"
	"time"
)

const TimeFormatLayout = "2006-01-02 15:04:05"
const TimeFormatYMDLayout = "2006-01-02"
const TimeFormatYMDHSLayout = "2006-01-02-15-04"
const TimeMilliFormatLayout = "2006-01-02 15:04:05.000"

// DayStart current day start
func DayStart(t time.Time) time.Time {
	location, _ := time.LoadLocation("Asia/Shanghai")
	date := time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 1, location)
	return date
}

// DayEnd current day end
func DayEnd(t time.Time) time.Time {
	location, _ := time.LoadLocation("Asia/Shanghai")
	date := time.Date(t.Year(), t.Month(), t.Day(), 0, 0, 0, 0, location)
	end := date.Add(time.Hour*24 - time.Microsecond)
	return end
}

// UnixMilli time to milli
func UnixMilli(t time.Time) int64 {
	return t.UnixNano() / 1e6
}

// UnixSecond time to second
func UnixSecond(t time.Time) int64 {
	return t.UnixNano() / 1e9
}

// Time2ChinaStr time to string
func Time2ChinaStr(t time.Time) string {
	location, _ := time.LoadLocation("Asia/Shanghai")
	return t.In(location).Format(TimeFormatLayout)
}

// Time2FormatStr time to string
func Time2FormatStr(t time.Time, format string) string {
	return t.Format(format)
}

// Time2MilliStr time to string with milli
func Time2MilliStr(t time.Time) string {
	return t.Format(TimeMilliFormatLayout)
}

// Int2Time milli to time
func Int2Time(timestamp int64) time.Time {
	return time.Unix(0, timestamp*1e6)
}

// Int2TimePoint milli to time
func Int2TimePoint(timestamp int64) *time.Time {
	unix := time.Unix(0, timestamp*1e6)
	return &unix
}

// TimePoint time to time point
func TimePoint(t time.Time) *time.Time {
	return &t
}

// Str2Time str to chinese time
func Str2Time(str string) (*time.Time, error) {
	location, _ := time.LoadLocation("Asia/Shanghai")
	locationTime, err := time.ParseInLocation(TimeFormatLayout, str, location)
	if err != nil {
		return nil, err
	}
	return &locationTime, nil
}

// Milli2ChinaStr milli to time
func Milli2ChinaStr(timestamp int64) string {
	t := Int2Time(timestamp)
	return Time2ChinaStr(t)
}

// Period get period num and unit by seconds for num(d/M/w/h/m/s)
func Period(seconds uint64) (uint, string) {
	day := uint64(time.Hour.Seconds()) * 24
	week := day * 7
	month := day * 30
	fmt.Printf(" seconds : %d day %d \n", seconds, day)
	if seconds > month {
		return uint(seconds / month), "M"
	}
	if seconds > week {
		return uint(seconds / week), "w"
	}
	if seconds > day {
		return uint(seconds / day), "d"
	}
	if seconds > uint64(time.Hour.Seconds()) {
		return uint(seconds / uint64(time.Hour.Seconds())), "h"
	}
	if seconds > uint64(time.Minute.Seconds()) {
		return uint(seconds / uint64(time.Minute.Seconds())), "m"
	}
	return uint(seconds), "s"
}
